package com.squirrel.michale.search5;

/**
 * @author guanhao 观浩
 * @version 1.0.0.0
 * @createTime 2023/1/19 12:05 PM
 * @company Michale Squirrel
 * @link
 * @description
 *
 * 74. 搜索二维矩阵
 * 中等
 * 750
 * 相关企业
 * 编写一个高效的算法来判断 m x n 矩阵中，是否存在一个目标值。该矩阵具有如下特性：
 *
 * 每行中的整数从左到右按升序排列。
 * 每行的第一个整数大于前一行的最后一个整数。
 *
 *
 * 示例 1：
 *
 *
 * 输入：matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
 * 输出：true
 * 示例 2：
 *
 *
 * 输入：matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
 * 输出：false
 *
 *
 * 提示：
 *
 * m == matrix.length
 * n == matrix[i].length
 * 1 <= m, n <= 100
 * -104 <= matrix[i][j], target <= 104
 */
public class LeetCode0074 {


    public boolean searchMatrix(int[][] matrix, int target) {

        int rows = matrix.length;//行数
        int columns = matrix[0].length;//列数

        int left = 0;
        int right = rows*columns - 1;

        int middle = 0;
        while (left <= right) {
            middle = left + ((right - left) >> 1);
            int element = matrix[middle / columns][middle % columns];
            if (element > target) {
                right = middle - 1;
            } else if (element == target) {
                return true;
            } else {
                left = middle + 1;
            }
        }
        return false;

    }


    public static void main(String[] args) {

        LeetCode0074 leetCode0074 = new LeetCode0074();

        int[][] matrix = new int[][]{{1,3,5,7},{10,11,16,20},{23,30,34,60}};
        int target = 13;
        System.out.println(leetCode0074.searchMatrix(matrix, target));


        int[][] matrix2 = new int[][]{{1,3,}};
        int target2 = 3;
        System.out.println(leetCode0074.searchMatrix(matrix2, target2));




    }

}
